// components/game_vs/game_vs.js
import LAN from '../../utils/lan';

const app = getApp();
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    avatarUrl:{
      type:String,
      value:''
    },
    nickName:{
      type:String,
      value:''
    },
    remoterInfo:{
      type:Object,
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    address:'0.0.0.0',
    port:0,
    remoter:null,
    time:0,

  },

  /**
   * 组件的方法列表
   */
  methods: {
    setIsRobot(value){
      this.setData({IsRobot:value});
      if(this.data.client) this.data.client.close();
      this.data.server.close();
      var rem={
        avatarUrl:null,
        nickName:"Robot",
        port:55555,
      }
      this.setData({remoter:rem});
      // this.setData({avatarUrl:"null"});
      this.setData({nickName:"玩家"});
    },
    joinGame(){
      // const { port } = this.data;
      const { remoterInfo, nickName, avatarUrl } = this.properties;
      wx.showToast({
        title: 'joinGame',
        icon:"none",
      });
      LAN.sendMessage({
        remoteInfo:remoterInfo,
        message: { intent:'join' },
        success:res=>{
          switch(res.intent){
            case 'join_ok':
              this.startOtherGame(remoterInfo,res);
              wx.showToast({
                title: 'join_ok',
                icon:"none",
              });
              break;
            case 'join_fail':
              wx.showToast({
                title: "join_fail",
                icon:"none",
              });
              app.showToast(res.errMsg);
              break;
            default:
              let itt=res.intent;
              wx.showToast({
                title: "itt",
                icon:"none",
              });
              console.log('join not known error', res);
              break;
          }
        },
        fail(err){
          wx.showToast({
            title: "join fail",
            icon:"none",
          });
          console.error(err)
          app.showModal(err.errMsg)
        }
      })
    },
  
    exitGame(){
      const { remoter } = this.data;
      if(!remoter) return;
      LAN.sendMessage({
        remoteInfo:remoter,
        message:{ intent:'exit' },
        success:res=>{
          this.setData({
            remoter:null
          });
        },
        fail(err){
          console.error(err)
          app.showModal(err.errMsg)
        }
      })
    },
  
    startGame(remoteInfo,msg){
      if (this.data.client) return;
      if (msg?.port) remoteInfo.port = msg.port;
      const { nickName, avatarUrl } = this.properties;
      this.data.client = LAN.connectServer(remoteInfo,{
        config:{
          nickName,
          avatarUrl,
          port:this.data.server.getPort()
        },
        onDisconnect:res=>{
          this.setData({
            remoter:null
          });
          app.showModal({
            content:'连接超时了',
            showCancel:true,
            confirmText:'退出',
            success:(res)=>{
              if(!res.confirm) return;
              wx.navigateBack();
            }
          }); 
        },
        onConnect:res=>{
          // const { remoteInfo } = res;
          const { message:msg } = res;
          this.setData({
            remoter:{
              address:remoteInfo.address,
              port:remoteInfo.port,
              nickName:msg.nickName,
              avatarUrl:msg.avatarUrl
            }
          });
          app.showToast('加入游戏成功');
        },
        onReceive:res=>{
          const { message } = res;
          switch(message?.intent){
            case 'keep_connect':
              if(!this.data.remoter){
                this.setData({
                  remoter:res.remoteInfo
                });
              }
              if(message.otime){
                this.setData({
                  time:message.otime
                });
              }
              break;
            default:
              console.log('client onReceive +++++++',message)
          }
        }
      });
    },
  
    getMyGameData(isInit){
      const gameChess = this.getGameChess();
      if(isInit) gameChess.initData();
      return gameChess.getData();
      //需要加的函数
    },
  
    startOtherGame(remoteInfo,msg){
      const { gameData } = msg;
      //需要修改
      const gameChess = this.getGameChess();
      gameChess.initData();
      this.startGame(remoteInfo,msg);
    },

    syncAttack(remoteInfo,msg){
      const gameChess = this.getGameChess();
      if(msg.gameData==undefined) {
        console.error({ errMsg:'not identify piece', data:msg.gameData });
        app.showModal({
          content:'游戏数据同步出现错误,是否重新加入',
          showCancel:false,
          confirmText:'重新加入',
          success:res=>{
            if(!res.confirm) {
              return;
            }
            if(this.properties.remoterInfo){
              this.joinGame();
            }else{
              this.exitGame();
            }
          }
        })
        return;
      }
      gameChess.passiveMsgResp(msg.gameData);
    },
  
    sendAttackAnother(gameData){
      const { remoter } = this.data;
      // console.log("this.data:",this.data);
      // console.log("remoter:",remoter);
      // console.log("gameData:",gameData.data);

      if(!remoter) return;
      LAN.sendMessage({
        remoteInfo:remoter,
        message:{
          intent:'Attack',
          gameData
        }
      })

    },
     
    gameChessReady() {
      const { remoterInfo, nickName, avatarUrl } = this.properties;
      if(!remoterInfo) {
        console.log('joinGame:not find remoterInfo');
        return;
      }
      this.joinGame();
    }, 

    onAttackAnother(e){
      console.log("触发事件onAttackAnother")
      this.sendAttackAnother(e.detail);
    },

    getGameChess(){
      return this.selectComponent('#FTWindow');
    },

    resetRobot(){
      const gameData = this.getMyGameData(true);
    },

    resetGame(){
      const gameData = this.getMyGameData(true);
      if(this.data.remoter==undefined){
        wx.showToast({
          title: 'reset Remo no',
          icon:"error"
        })
      }
      LAN.sendMessage({
        remoteInfo:this.data.remoter,
        message:{
          intent:'restart',
          gameData
        }
      })
    }
  },

  lifetimes:{
    ready(){
      const { nickName, avatarUrl } = this.properties;
      let server = LAN.createServer({
        config:{
          port:55555,
          nickName, avatarUrl,
        },
        onError(err){
          if(!err.errMsg) console.error(err);
          app.showModal({
            content:err.errMsg || '未知错误',
            success(res){}
          })
        },
        onReceive:res=>{
          const { localInfo, remoteInfo, message } = res;
          switch(message?.intent){
            case 'scan':
              return {
                nickName:this.properties.nickName,
                avatarUrl:this.properties.avatarUrl,
                gameState:this.data.remoter ? true : false,
                gameName:'疯狂的火柴人',
                gameID:'FTWindow'
              };
            case 'join':
              {
                const { remoter, address, port } = this.data;
                if(remoter && remoter.address!=remoteInfo.address) {
                  return {
                    intent:'join_fail',
                    errMsg:'对方在游戏中'
                  };
                }

                let data = this.getMyGameData();
                wx.showToast({
                  title: 'Get join',
                })
                return {
                  intent:'join_ok',
                  // nickName,
                  // avatarUrl,
                  port,
                  gameData:data
                };
              }    
            case 'exit':
              {
                this.setData({
                  remoter:null
                });
                app.showModal('对方退出了游戏');
                break;
              }
            case 'restart':
              {
                this.startOtherGame(remoteInfo,message);
                app.showToast('重新开始游戏');
                break;
              }
            case 'Attack':
              //调用受击处理函数
              this.syncAttack(remoteInfo,message);
              break;
            case 'keep_connect':
              if(message?.otime){
                this.setData({
                  time:message.otime
                });
              }
              break;
            default:
              console.log('server onReceive ++++++++++++=',message)
              
          }
          return { errMsg:'ok' };
        },
        onConnect:res=>{
          console.log('server onConnect+++++++',res)
          const { remoteInfo, message } = res;
          this.setData({
            remoter:{
              address:remoteInfo.address,
              port:message.port || remoteInfo.port,
              avatarUrl:message.avatarUrl,
              nickName:message.nickName
            }
          });
          app.showToast('对方已连接');
        },
        onDisconnect:res=>{
          console.log('server onDisconnect+++++++',res)
          this.setData({
            remoter:null
          });
          app.showModal({
            content:'连接超时了,是否退出',
            showCancel:true,
            confirmText:'退出',
            success:(res)=>{
              if(!res.confirm) return;
              wx.navigateBack()
            }
          });
        }
      });
      this.data.server = server;
      this.setData({
        port:server.getPort()
      })
    },
    detached(){
      if(this.data.client) this.data.client.close();
      this.data.server.close();
    }
  }

})
